package com.diyizu.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diyizu.youdianda.common.PageResult;
import com.diyizu.youdianda.common.R;
import com.diyizu.youdianda.entity.YddUser;
import com.diyizu.youdianda.service.YddUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequestMapping("/ydd_user")
public class YddUserController {

    @Autowired
    private YddUserService yddUserService;

    /**
     * 根据id查询用户详情
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public R<YddUser> getById(Integer id){
        log.info("前端传过来的数据:" ,id);
        YddUser yddUser = yddUserService.getById(id);
        return R.success(yddUser);
    }

    /**
     * 使用户列表分页查询
     * @param sex
     * @param username
     * @param mobile
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public R page(String sex,String username,String mobile,String page,String limit){
        log.info("sex = {},username = {},mobile = {},page = {},limit = {}",sex,username,mobile,page,limit);
        //数据类型转换
        int pages = Integer.parseInt(page);
        int limits = Integer.parseInt(limit);
        //构造分页构造器
        Page pageInfo = new Page(pages,limits);

        //构造条件构造器
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        //添加条件
        wrapper.eq(StringUtils.isNotEmpty(sex),YddUser::getSex,sex);
        wrapper.like(StringUtils.isNotEmpty(username),YddUser::getUsername,username);
        wrapper.eq(StringUtils.isNotEmpty(mobile),YddUser::getMobile,mobile);
        //执行查询
        yddUserService.page(pageInfo,wrapper);

        //封装结果集
        PageResult pageResult =new PageResult();
        pageResult.setData(pageInfo.getRecords());
        pageResult.setCurrentPage(pageInfo.getCurrent());
        pageResult.setCount(pageInfo.getTotal());
        pageResult.setPageSize(pageInfo.getSize());
        pageResult.setTotalPages(pageInfo.getPages());

        return R.success(pageResult);

    }

    @PostMapping("/add")
    public R add(@RequestBody YddUser yddUser){
        yddUserService.save(yddUser);
        return R.success("用户保存成功");
    }

    @GetMapping("/del")
    public R del(String id){
        int uid=Integer.parseInt(id);
        yddUserService.removeById(uid);
        return R.success("用户删除成功");
    }

    @PostMapping("/update")
    public R update(@RequestBody YddUser yddUser){
        yddUserService.updateById(yddUser);
        return R.success("用户更新成功");
    }

}
